home *** CD-ROM | disk | FTP | other *** search
- Path: symiserver2.symantec.com!elazzar1
- From: elazzaro@symantec.com (Erin Lazzaro)
- Newsgroups: comp.lang.c++
- Subject: Re: Did I Miss Something?
- Date: Tue, 09 Apr 96 18:58:06 GMT
- Organization: Symantec Corp.
- Message-ID: <4ke8p7$i8g@symiserver2.symantec.com>
- References: <N.040396.105136.51@ix.netcom.com>
- <4k01o7$sl2@grimsel.zurich.ibm.com> <N.040496.100620.06@ix.netcom.com>
- NNTP-Posting-Host: 155.64.65.78
- X-Newsreader: News Xpress Version 1.0 Beta #4
-
- In article <N.040496.100620.06@ix.netcom.com>,
- jhewett@ix.netcom.com (Jerry Hewett) wrote:
- >So if my theory that the act of calling a constructor allocates the necessary
- >memory (like strdup automagically calls malloc to create space in the heap)
- is
- >in error, then the original example (line_of_text = input_line) indeed does
- not
- >carve out a chuck of RAM big enough to hold "small box"? So even though this
- >works when I compile it, in actuality it is undefined behavior?
-
- You're making this way too hard. Step back and take a breath. This is _not_
- new behavior in C++ -- it's the way C has always done it.
-
- Take the example (pure C)
- char * p;
- p = "This is a string constant";
-
- "This is a string constant" is a string constant. In most implementations,
- this means that the compiler allocates space for it in a "string table",
- which is in initialized global storage. At the point of reference, it
- replaces it with the address in the string table. So the assignment
- compiles to
- p = 0xXXXXX; /* some address in the string table */
- p hasn't been redefined in any way; it's still just a pointer.
-
- Don't confuse this "string table" with a Windows stringtable; this is an
- internal data structure within the compiler. All you know is that you are
- pointing at a string constant (which may be implemented some other way).
-
- A statement like
- char * p = "This is a string constant";
- does exactly the same thing. p isn't const; it is currently pointing to
- memory which is const, but it can be reassigned.
-
- A constructor like this
- box::box(char * inputline)
- {
- m_inputline = inputline; // initialize a member of type char*
- }
- does not allocate memory. It causes m_inputline to point to the same
- (previously allocated) memory as inputline.
-
- Here's some bad code (I use malloc instead of new to make it clearer to C
- readers):
- p = malloc(30);
- strcpy( p, "This is a malloc'd string");
- box1 = new box(p);
- free(p); // box1->m_inputline now points to free'd memory
-
- A declaration like
- box box1("This is a constant string");
- allocates a box whose m_inputline points to a string constant.
- m_inputline is not const; it can be reassigned later. It points
- (currently) into const memory.
-
- I think you have been misled by unfamiliar terms to think that you are
- dealing with unfamiliar concepts. I hope this is clearer.
-
- -Erin Lazzaro
-